//
//  LoginButton.swift
//  PhotoLine
//
//  Created by 吴帅 on 17/9/14.
//  Copyright © 2017年 PhotoLine. All rights reserved.
//

import UIKit

class LoginButton: UIButton {
    
    var originalFrame:CGRect?; ///原始frame
    var title:String?; ///原始title
    lazy var path:UIBezierPath? = {
        let lazyPath = UIBezierPath.init()
        //指定圆形的圆心和开始结束的角度   clockwise:是否顺时针
        lazyPath.addArc(withCenter: CGPoint.init(x: 22, y: 22), radius: 15, startAngle: -CGFloat(Double.pi*2), endAngle: 0, clockwise: true)
        
        return lazyPath;
    }();
    lazy var round:UIView? = {
        let lazyRound = UIView.init(frame:CGRect.init(x: 10, y: 10, width: 3, height: 3));
        lazyRound.backgroundColor = UIColor.white;
        return lazyRound;
    }();

    override init(frame: CGRect) {
        super.init(frame: frame);
        self.layer.cornerRadius = 5;
        self.layer.masksToBounds = true;
        
        self.originalFrame = frame; // 保存原始frame
        
//        self.addTarget(self, action: #selector(LoginButton.tapAction), for: UIControlEvents.touchUpInside);
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        self.isEnabled = false;
        title = self.titleLabel?.text; // 保存原始title
        UIView.animate(withDuration: 0.3, animations: {
            self.frame = CGRect.init(x: 0, y: 25, width: self.frame.height, height: self.frame.height);
            self.center = CGPoint.init(x: (self.superview?.frame.width)!/2.0, y: self.frame.origin.y+self.frame.height/2.0);
            self.layer.cornerRadius = self.frame.height/2.0;
            self.setTitle("", for: UIControlState.normal);
            }) { (finish) in
                self.addSubview(self.round!);
                self.loadingAnimation();
                self.targetAction();
        };
    }
    
    /// 还原frame
    public func endLoading() {
        self.round?.removeFromSuperview();
        UIView.animate(withDuration: 0.3, animations: {
            self.frame = self.originalFrame!;
            self.layer.cornerRadius = 5;
            }) { (finish) in
                self.setTitle(self.title, for: UIControlState.normal);
                self.isEnabled = true;
        };
    }
    
    // 加载动画
    func loadingAnimation() {
        
        let anim = CAKeyframeAnimation.init(keyPath: "position")
        anim.path = self.path?.cgPath
        anim.fillMode = kCAFillModeForwards
        anim.calculationMode = kCAAnimationCubic
        anim.repeatCount = HUGE
        anim.duration = 1
        self.round?.layer.add(anim, forKey: "animation")
    }
    
    func targetAction() {
        self.sendActions(for: UIControlEvents.touchUpInside);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
